import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:fluwx/fluwx.dart';
import 'package:http/http.dart' as http;
import 'package:image/image.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';

import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../EcyEventBus.dart';
import 'EcyStorage.dart';

class EcyWxUtil {
  factory EcyWxUtil() => _instance;
  static late final EcyWxUtil _instance = EcyWxUtil._internal();
  late BuildContext context;

  Fluwx? fluwx;
  FluwxCancelable? _wxSubscription;

  EcyWxUtil._internal() {
    EcyLogger.log("EcyWxUtil init");
    init();
  }

  init() async {
    if (fluwx != null || _wxSubscription != null) return;

    fluwx = Fluwx();
    await fluwx?.registerApi(
        appId: "wx26e818ed97314bc4",
        universalLink: "https://www.goodsqi.com/app/");
    var result = await fluwx?.isWeChatInstalled;
    debugPrint('is installed $result');

    _wxSubscription = fluwx?.addSubscriber((wxResponse) {
      EcyStorage.getString(EcyEventConst.kPayedOrderId).then((orderId) {
        EcyRouter.pushReplacement(this.context, EcyRouter.orderInfoPage, orderId);
      }).catchError((onError) {
        EcyRouter.pushReplacement(this.context, EcyRouter.orderInfoPage, "");
      });
      if (wxResponse.isSuccessful) {
        EcyLogger.log(wxResponse.toString());
      } else {
        EcyLogger.error(wxResponse.toString());
      }
      EcyEventBus().emit(EcyEventConst.kPaySuccess);
      EcyEventBus().emit(EcyEventConst.kOnOrder);
    });
  }

  static shareText(String txt) async {
    Fluwx fluwx = Fluwx();
    Map<String, dynamic> shareOb = json.decode(txt);
    String picUrl = shareOb["shareImageUrl"] ?? "";
    if (picUrl.isEmpty) {
      fluwx.share(WeChatShareWebPageModel(shareOb["shareUrl"] ?? "",
          title: shareOb["shareTitle"] ?? "", scene: WeChatScene.session));
    } else {
      EasyLoading.show(status: '加载中...');
      Uint8List? img = await EcyWxUtil.fetchImageAsUint8List(picUrl);
      // 定义文件保存路径
      String filePath = await getImageSavePath(Uuid().v4());
      File file = await uint8ListToFile(img!, filePath);
      File file2 = await compressImage(file);
      Uint8List? img2 = await fileToUint8List(file2);
      EasyLoading.dismiss();
      if (shareOb != null) {
        fluwx.share(WeChatShareWebPageModel(shareOb["shareUrl"] ?? "",
            thumbData: img2 ?? null,
            title: shareOb["shareTitle"] ?? "",
            scene: WeChatScene.session));
      }
    }
  }

  static Future<Uint8List> fileToUint8List(File file) async {
    // 读取文件内容为 Uint8List
    Uint8List bytes = await file.readAsBytes();
    return bytes;
  }

  static Future<String> getImageSavePath(String fileName) async {
    // 获取应用文档目录
    final Directory appDocDir = await getApplicationDocumentsDirectory();

    // 构建文件路径
    final String filePath = join(appDocDir.path, fileName);

    return filePath;
  }

  static Future<File> compressImage(File file) async {
    final bytes = await file.readAsBytes();
    final img = decodeImage(bytes);

    final resizedImg = copyResize(img!, width: 40); // 设置目标宽度
    final compressedBytes = encodeJpg(resizedImg, quality: 20); // 压缩质量，0-100

    final compressedFile = File(file.path + '_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    return compressedFile;
  }

  static Future<Uint8List?> fetchImageAsUint8List(String imageUrl) async {
    final response = await http.get(Uri.parse(imageUrl));
    if (response.statusCode == 200) {
      // If the server returns a 200 OK response, return the image as Uint8List
      return response.bodyBytes;
    } else {
      return null;
      // If the server did not return a 200 OK response, throw an exception.
      throw Exception('Failed to load image');
    }
  }

  static Future<File> uint8ListToFile(
      Uint8List uint8List, String filePath) async {
    // 创建一个文件
    final file = File(filePath);

    // 将 Uint8List 写入文件
    await file.writeAsBytes(uint8List);

    return file;
  }

  auth() {
    Fluwx fluwx = Fluwx();
    fluwx.authBy(
        which: NormalAuth(
            scope: 'snsapi_userinfo', state: 'wechat_sdk_demo_test'));
  }

  pay(result, BuildContext context) {
    this.context = context;
    Fluwx fluwx = Fluwx();
    return fluwx.pay(
        which: Payment(
      appId: result['appId'],
      partnerId: result['partnerId'],
      prepayId: result['prepayId'],
      packageValue: result['packageValue'],
      nonceStr: result['nonceStr'],
      timestamp: int.parse(result['timeStamp']),
      sign: result['paySign'],
    ));
  }
}
